package cn.ulc.socket.weapp.controller;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import cn.ulc.common.util.Result;
import cn.ulc.socket.weapp.model.param.ShopCartParam;
import cn.ulc.socket.weapp.service.ShopCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.Min;

@Validated
@RestController
@RequestMapping(value = "/wechat/shopcart")
public class ShopCartController {
    private static final Log log = LogFactory.get();
    @Autowired
    ShopCartService shopCartService;

    @GetMapping("")
    public Result findList(){
        return Result.success(shopCartService.findList());
    }

    //保存商品到购物车
    @PostMapping("")
    public Result save(@Validated @RequestBody ShopCartParam param, BindingResult result){
        if(result.hasErrors()) {
            log.error("保存到购物车信息有误",result.getFieldError().getDefaultMessage());
            return Result.fail(result.getFieldError().getDefaultMessage());
        }
        return Result.success(shopCartService.save(param));
    }

    //更新数量
    @PutMapping("/changeNum")
    public Result changeNum(@Validated @RequestBody ShopCartParam param){
        return Result.success(shopCartService.changeNum(param));
    }
    //购物车删除
    @DeleteMapping("/{id}")
    public Result deleted(@PathVariable @Min(1) Long id){
        return Result.success(shopCartService.deleted(id));
    }
}
